home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java Primer Plus
/
Java Primer Plus (Waite Group Proess)(1996).iso
/
chapter14
/
prodcons.java
< prev
next >
Wrap
Text File
|
1995-12-31
|
2KB
|
95 lines
/* Producer/Consumer problem */
/* The bounded buffer */
class theTray {
static final int traysize = 10;
static int count,posW,posF = 0;
static int tray[] = new int[traysize];
/* put an egg if there is room */
public synchronized void layegg(int x) throws InterruptedException {
if (count == traysize) {
System.out.println("Wippy waiting...");
wait();
}
count++;
tray[posW] = x;
posW = (posW + 1)%10;
System.out.println("Count: " + count + " Wippy laid egg #" + x);
if (count == 1) notify();
}
/* remove an egg, if there are any */
public synchronized int getegg() throws InterruptedException {
int x;
if (count == 0) {
System.out.println("Farmer waiting...");
wait();
}
count--;
x = tray[posF];
posF = (posF+1)%10;
System.out.println("Count: " + count + " Farmer got egg #" + x);
if (count == traysize-1) notify();
return x;
}
}
/* The Producer */
class Wippy extends Thread {
theTray B;
int q=200;
Wippy(theTray B) { this.B = B; }
public void run() {
int a=0;
while (q-->0) {
try {
B.layegg(a);
a = (a+1)%100000;
sleep((int)(20*Math.random()));
} catch (InterruptedException e) ;
}
}
}
/* The consumer */
class Farmer extends Thread {
theTray B;
int q=200;
Farmer(theTray B) { this.B = B; }
public void run() {
int a=0;
while (q-->0) {
try {
a = B.getegg();
sleep((int)(20*Math.random())+10);
} catch (InterruptedException e) ;
}
}
}
/* class to start the process */
class runner {
public static void main(String args[]) {
theTray B = new theTray();
Wippy W = new Wippy(B);
Farmer F = new Farmer(B);
W.start();
F.start();
}
}